<template>
  <div class="message-center">
    <!-- 左侧消息分类 -->
    <div class="message-sidebar">
      <div class="sidebar-header">
        <h3>{{ $t('message.messageCategories') }}</h3>
      </div>
      <div class="category-list">
        <div 
          v-for="category in messageCategories" 
          :key="category.id"
          class="category-item"
          :class="{ 'active': selectedCategory === category.id }"
          @click="selectCategory(category.id)"
        >
          <span class="category-name">{{ category.name }}</span>
          <el-badge 
            v-if="category.unreadCount > 0" 
            :value="category.unreadCount" 
            class="category-badge"
            :hidden="category.unreadCount === 0"
            type="danger"
          />
        </div>
      </div>
    </div>

    <!-- 右侧消息列表 -->
    <div class="message-main-container">
      <div class="list-header">
        <h3>{{ $t('message.messageList') }}</h3>
        <div class="list-actions">
          <el-button size="small" @click="refreshMessages" :loading="refreshing">
            <el-icon><Refresh /></el-icon>
            {{ $t('message.refresh') }}
          </el-button>
          <el-button size="small" @click="markAllAsRead" :disabled="unreadCount === 0">
            {{ $t('message.markAllAsRead') }}
          </el-button>
          <el-button size="small" type="danger" @click="deleteAllMessages">
            {{ $t('message.clearAllMessages') }}
          </el-button>
        </div>
      </div>
      
      <div class="message-list">
        <div v-if="isLoading" class="loading-container">
          <el-skeleton :rows="5" animated />
        </div>
        
        <div v-else-if="filteredMessages.length === 0" class="empty-state">
          <el-empty :description="$t('message.noMessages')">
            <template #description>
              <p>{{ $t('message.noMessagesInCategory') }}</p>
              <p v-if="selectedCategory === 'all'" style="font-size: 12px; color: #999; margin-top: 8px;">
                {{ $t('message.noMessageData') }}
              </p>
            </template>
          </el-empty>
        </div>
        
        <div v-else>
          <div
            v-for="message in filteredMessages"
            :key="message.notificationId"
            class="message-item"
            :class="{ 
              'active': selectedMessage?.notificationId === message.notificationId,
              'unread': !message.isRead 
            }"
            @click="selectMessage(message)"
          >
            <div class="message-indicator">
              <div class="indicator-dot" :class="{ 'unread': !message.isRead }"></div>
              <el-badge 
                v-if="!message.isRead" 
                :value="1" 
                class="message-badge"
                type="danger"
                :hidden="message.isRead"
              />
            </div>
            <div class="message-content">
              <div class="message-title">{{ message.title }}</div>
              <div class="message-preview">{{ message.content || $t('message.noContent') }}</div>
              <div class="message-meta">
                <span class="message-type">{{ getMessageTypeLabel(message.messageType) }}</span>
                <span class="message-time">{{ formatTime(message.sentTime) }}</span>
              </div>
            </div>
            <div class="message-actions">
              <el-button 
                v-if="!message.isRead"
                size="small" 
                type="primary"
                @click.stop="markAsRead(message.notificationId)"
              >
                {{ $t('message.markAsRead') }}
              </el-button>
              <el-button 
                size="small" 
                type="danger" 
                @click.stop="deleteMessage(message.notificationId)"
              >
                {{ $t('message.delete') }}
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 分页组件 -->
      <div v-if="pagination.totalPages > 1" class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50]"
          :total="pagination.totalMessages"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 消息详情弹窗 -->
    <el-dialog
      v-model="showDetail"
      :title="messageDetail?.title || $t('message.messageDetail')"
      width="600px"
      :before-close="closeDetail"
      class="message-detail-dialog"
    >
      <div v-if="messageDetail" class="detail-content">
        <div class="detail-item">
          <span class="detail-label">{{ $t('message.title') }}</span>
          <span class="detail-value">{{ messageDetail.title }}</span>
        </div>
        
        <div class="detail-item">
          <span class="detail-label">{{ $t('message.type') }}</span>
          <span class="detail-value">{{ getMessageTypeLabel(messageDetail.messageType) }}</span>
        </div>
        
        <div class="detail-item">
          <span class="detail-label">{{ $t('message.recipientType') }}</span>
          <span class="detail-value">{{ messageDetail.recipientType === 'student' ? $t('message.student') : $t('message.enterprise') }}</span>
        </div>
        
        <div class="detail-item">
          <span class="detail-label">{{ $t('message.sentTime') }}</span>
          <span class="detail-value">{{ formatFullTime(messageDetail.sentTime) }}</span>
        </div>
        
        <div class="detail-item">
          <span class="detail-label">{{ $t('message.status') }}</span>
          <span class="detail-value" :class="{ 'unread-status': !messageDetail.isRead, 'read-status': messageDetail.isRead }">
            {{ messageDetail.isRead ? $t('message.read') : $t('message.unread') }}
          </span>
        </div>
        
        <div class="detail-item full-width">
          <span class="detail-label">{{ $t('message.content') }}</span>
          <div class="detail-content-text" v-html="formatMessageContent(messageDetail.content)"></div>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button 
            v-if="messageDetail && !messageDetail.isRead"
            type="primary"
            @click="markDetailAsRead"
          >
            {{ $t('message.markAsRead') }}
          </el-button>
          <el-button 
            type="danger" 
            @click="deleteDetailMessage"
          >
            {{ $t('message.deleteMessage') }}
          </el-button>
          <el-button @click="closeDetail">{{ $t('message.close') }}</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useNotificationsStore } from '@/store/modules/notifications'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh, Close } from '@element-plus/icons-vue'
import { useI18n } from 'vue-i18n'

// 使用i18n
const { t } = useI18n()

// 使用Pinia store
const notificationsStore = useNotificationsStore()

// 响应式数据
const selectedCategory = ref('all')
const selectedMessage = ref(null)
const loading = ref(false)
const refreshing = ref(false)
const messageDetail = ref(null)
const showDetail = ref(false)

// 计算属性
const notifications = computed(() => notificationsStore.notifications)
const unreadCount = computed(() => notificationsStore.unreadCount)
const isLoading = computed(() => notificationsStore.loading)
const pagination = computed(() => notificationsStore.pagination)

// 消息分类
const messageCategories = computed(() => [
  {
    id: 'all',
    name: t('message.allMessages'),
    unreadCount: notifications.value.filter(n => !n.isRead).length
  },
  {
    id: 'unread',
    name: t('message.unreadMessages'),
    unreadCount: notifications.value.filter(n => !n.isRead).length
  },
  {
    id: 'resume_review',
    name: t('message.resumeReview'),
    unreadCount: notifications.value.filter(n => n.messageType === 'resume_review' && !n.isRead).length
  },
  {
    id: 'application_recommend',
    name: t('message.applicationRecommend'),
    unreadCount: notifications.value.filter(n => n.messageType === 'application_recommend' && !n.isRead).length
  },
  {
    id: 'enterprise_contact',
    name: t('message.enterpriseContact'),
    unreadCount: notifications.value.filter(n => n.messageType === 'enterprise_contact' && !n.isRead).length
  },
  {
    id: 'password_change',
    name: t('message.passwordChange'),
    unreadCount: notifications.value.filter(n => n.messageType === 'password_change' && !n.isRead).length
  },
  {
    id: 'system_notification',
    name: t('message.systemNotification'),
    unreadCount: notifications.value.filter(n => n.messageType === 'system_notification' && !n.isRead).length
  }
])

// 根据分类筛选消息
const filteredMessages = computed(() => {
  let messages = notifications.value
  
  switch (selectedCategory.value) {
    case 'unread':
      messages = messages.filter(n => !n.isRead)
      break
    case 'resume_review':
      messages = messages.filter(n => n.messageType === 'resume_review')
      break
    case 'application_recommend':
      messages = messages.filter(n => n.messageType === 'application_recommend')
      break
    case 'enterprise_contact':
      messages = messages.filter(n => n.messageType === 'enterprise_contact')
      break
    case 'password_change':
      messages = messages.filter(n => n.messageType === 'password_change')
      break
    case 'system_notification':
      messages = messages.filter(n => n.messageType === 'system_notification')
      break
    default:
      // 全部消息
      break
  }
  
  return messages.sort((a, b) => new Date(b.sentTime) - new Date(a.sentTime))
})

// 获取消息类型标签
const getMessageTypeLabel = (messageType) => {
  const typeMap = {
    'resume_review': t('message.messageTypeResumeReview'),
    'application_recommend': t('message.messageTypeApplicationRecommend'),
    'enterprise_contact': t('message.messageTypeEnterpriseContact'),
    'password_change': t('message.messageTypePasswordChange'),
    'system_notification': t('message.messageTypeSystemNotification')
  }
  return typeMap[messageType] || messageType
}

// 选择分类
const selectCategory = (categoryId) => {
  selectedCategory.value = categoryId
  // 重置选中的消息
  selectedMessage.value = null
  // 选择第一条消息（不弹出详情）
  if (filteredMessages.value.length > 0 && filteredMessages.value[0]) {
    selectedMessage.value = filteredMessages.value[0]
  }
}

// 选择消息
const selectMessage = async (message) => {
  selectedMessage.value = message
  
  try {
    // 直接调用API获取消息详情
    const response = await fetch(`/api/api/v1/student/notifications/${message.notificationId}`, {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('access_token')}`,
        'Content-Type': 'application/json'
      }
    })
    
    if (response.ok) {
      const result = await response.json()
      if (result.code === 200 && result.data) {
        messageDetail.value = result.data
        showDetail.value = true
      } else {
        throw new Error(result.message || t('message.getMessageDetailFailed'))
      }
    } else {
      throw new Error(t('message.networkRequestFailed'))
    }
    
    // 如果消息未读，自动标记为已读
    if (message && !message.isRead && message.notificationId) {
      await markAsRead(message.notificationId)
    }
  } catch (error) {
    console.error('获取消息详情失败:', error)
    ElMessage.error(t('message.getMessageDetailFailed'))
  }
}

// 标记消息为已读
const markAsRead = async (messageId) => {
  if (!messageId) {
    return
  }
  
  try {
    await notificationsStore.markAsRead(messageId)
    
    // 立即更新本地消息状态，让红点消失
    const message = notifications.value.find(n => n.notificationId === messageId)
    if (message) {
      message.isRead = true
    }
    
    // 更新选中的消息状态
    if (selectedMessage.value && selectedMessage.value.notificationId === messageId) {
      selectedMessage.value.isRead = true
    }
    
    // 更新消息详情状态
    if (messageDetail.value && messageDetail.value.notificationId === messageId) {
      messageDetail.value.isRead = true
    }
    
    ElMessage.success(t('message.markAsReadSuccess'))
  } catch (error) {
    console.error('标记已读失败:', error)
    ElMessage.error(t('message.markAsReadFailed'))
  }
}

// 删除消息
const deleteMessage = async (messageId) => {
  try {
    await ElMessageBox.confirm(
      t('message.confirmDeleteMessage'),
      t('common.warning'),
      {
        confirmButtonText: t('common.confirm'),
        cancelButtonText: t('common.cancel'),
        type: 'warning'
      }
    )
    
    await notificationsStore.deleteNotification(messageId)
    
    // 如果删除的是当前选中的消息，清空选择
    if (selectedMessage.value && selectedMessage.value.notificationId === messageId) {
      selectedMessage.value = null
    }
    
    // 如果删除的是当前显示详情的消息，关闭详情
    if (messageDetail.value && messageDetail.value.notificationId === messageId) {
      showDetail.value = false
      messageDetail.value = null
    }
    
    ElMessage.success(t('message.deleteMessageSuccess'))
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除消息失败:', error)
      ElMessage.error(t('message.deleteMessageFailed'))
    }
  }
}

// 标记所有消息为已读
const markAllAsRead = async () => {
  try {
    await ElMessageBox.confirm(
      t('message.confirmMarkAllAsRead'),
      t('common.warning'),
      {
        confirmButtonText: t('common.confirm'),
        cancelButtonText: t('common.cancel'),
        type: 'warning'
      }
    )
    
    await notificationsStore.markAllAsRead()
    ElMessage.success(t('message.markAsReadSuccess'))
  } catch (error) {
    if (error !== 'cancel') {
      console.error('标记全部已读失败:', error)
      ElMessage.error(t('message.markAsReadFailed'))
    }
  }
}

// 清空所有消息
const deleteAllMessages = async () => {
  try {
    await ElMessageBox.confirm(
      t('message.confirmDeleteAllMessages'),
      t('common.warning'),
      {
        confirmButtonText: t('common.confirm'),
        cancelButtonText: t('common.cancel'),
        type: 'warning'
      }
    )
    
    await notificationsStore.deleteAllNotifications()
    
    // 清空选择状态
    selectedMessage.value = null
    messageDetail.value = null
    showDetail.value = false
    
    ElMessage.success(t('message.deleteAllMessagesSuccess'))
  } catch (error) {
    if (error !== 'cancel') {
      console.error('清空消息失败:', error)
      ElMessage.error(t('message.deleteAllMessagesFailed'))
    }
  }
}

// 刷新消息
const refreshMessages = async () => {
  refreshing.value = true
  try {
    await notificationsStore.refreshNotifications()
    ElMessage.success(t('message.refresh'))
  } catch (error) {
    console.error('刷新消息失败:', error)
    ElMessage.error(t('message.refresh'))
  } finally {
    refreshing.value = false
  }
}

// 关闭详情弹窗
const closeDetail = () => {
  showDetail.value = false
  messageDetail.value = null
}

// 标记详情消息为已读
const markDetailAsRead = async () => {
  if (messageDetail.value && messageDetail.value.notificationId) {
    await markAsRead(messageDetail.value.notificationId)
  }
}

// 删除详情消息
const deleteDetailMessage = async () => {
  if (messageDetail.value && messageDetail.value.notificationId) {
    await deleteMessage(messageDetail.value.notificationId)
  }
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.value.pageSize = size
  notificationsStore.loadNotifications()
}

const handleCurrentChange = (page) => {
  pagination.value.currentPage = page
  notificationsStore.loadNotifications()
}

// 格式化时间
const formatTime = (timeString) => {
  if (!timeString) return ''
  
  const now = new Date()
  const time = new Date(timeString)
  const diff = now - time
  
  const minutes = Math.floor(diff / (1000 * 60))
  const hours = Math.floor(diff / (1000 * 60 * 60))
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))
  const weeks = Math.floor(days / 7)
  const months = Math.floor(days / 30)
  const years = Math.floor(days / 365)
  
  if (minutes < 1) return t('message.justNow')
  if (minutes < 60) return t('message.minutesAgo', { minutes })
  if (hours < 24) return t('message.hoursAgo', { hours })
  if (days < 7) return t('message.daysAgo', { days })
  if (weeks < 4) return t('message.weeksAgo', { weeks })
  if (months < 12) return t('message.monthsAgo', { months })
  return t('message.yearsAgo', { years })
}

// 格式化完整时间
const formatFullTime = (timeString) => {
  if (!timeString) return ''
  return new Date(timeString).toLocaleString('zh-CN')
}

// 格式化消息内容
const formatMessageContent = (content) => {
  if (!content) return ''
  // 这里可以添加更多的内容格式化逻辑
  return content.replace(/\n/g, '<br>')
}

// 组件挂载时初始化
onMounted(async () => {
  // 获取当前用户信息
  const userId = localStorage.getItem('user_id')
  const userType = localStorage.getItem('user_type')
  
  // 传递用户信息作为参数
  const params = {
    recipient_id: userId,
    recipient_type: userType || 'student'
  }
  
  try {
    await notificationsStore.initializeNotifications(params)
    
    // 默认选择第一条消息（不弹出详情）
    if (filteredMessages.value.length > 0 && filteredMessages.value[0]) {
      selectedMessage.value = filteredMessages.value[0]
    }
  } catch (error) {
    console.error('消息初始化失败:', error)
  }
})
</script>

<style scoped>
.message-center {
  display: flex;
  height: 100%;
  background: transparent;
  overflow: hidden;
}

/* 左侧消息分类 */
.message-sidebar {
  width: 200px;
  background: #f5f5f5;
  border-right: 1px solid #ddd;
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  padding: 20px;
  border-bottom: 1px solid #ddd;
  background: #fff;
}

.sidebar-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.category-list {
  flex: 1;
  padding: 10px 0;
}

.category-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 20px;
  cursor: pointer;
  transition: background-color 0.2s;
  position: relative;
}

.category-item:hover {
  background-color: #e0e0e0;
}

.category-item.active {
  background-color: #e8f4fd;
  color: #1890ff;
}

.category-item.active::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 3px;
  background-color: #1890ff;
}

.category-name {
  font-size: 14px;
  font-weight: 500;
}

.category-badge {
  margin-left: 8px;
}

.message-badge {
  margin-left: 8px;
}

/* 右侧消息主容器 */
.message-main-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #fff;
}

.list-header {
  padding: 24px 30px !important;
  background: #fff !important;
  display: flex !important;
  justify-content: space-between !important;
  align-items: center !important;
  margin: 0 !important;
  min-height: 60px !important;
  position: relative !important;
  overflow: visible !important;
}

.list-header::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: -50vw;
  right: -50vw;
  height: 2px;
  background-color: #ddd;
  z-index: 1;
}

.list-header h3 {
  margin: 0 !important;
  font-size: 20px !important;
  font-weight: 600 !important;
  color: #333 !important;
  letter-spacing: 0.5px !important;
  line-height: 1.2 !important;
}

.list-actions {
  display: flex !important;
  gap: 12px !important;
  align-items: center !important;
}

.list-actions .el-button {
  font-size: 14px !important;
  padding: 10px 20px !important;
  border-radius: 0 !important;
  font-weight: 500 !important;
  border: 1px solid #ddd !important;
}

.list-actions .el-button--danger {
  background-color: #ff4d4f !important;
  border-color: #ff4d4f !important;
  color: white !important;
}

.list-actions .el-button--default {
  background-color: #f5f5f5 !important;
  border-color: #ddd !important;
  color: #333 !important;
}

.message-list {
  flex: 1;
  overflow-y: auto;
}

.loading-container {
  padding: 20px;
}

.empty-state {
  padding: 40px 20px;
  text-align: center;
}

.message-item {
  display: flex;
  align-items: flex-start;
  padding: 20px;
  border-bottom: 1px solid #eee;
  cursor: pointer;
  transition: background-color 0.2s;
  position: relative;
}

.message-item:hover {
  background-color: #f5f5f5;
}

.message-item.active {
  background-color: #e8f4fd;
  border-left: 3px solid #1890ff;
}

.message-item.unread {
  background-color: #fff7e6;
}

.message-item.unread:hover {
  background-color: #ffe7ba;
}

.message-indicator {
  margin-right: 12px;
  margin-top: 2px;
}

.indicator-dot {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background-color: #67c23a;
}

.indicator-dot.unread {
  background-color: #ff4d4f;
}

.message-content {
  flex: 1;
  min-width: 0;
}

.message-title {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.message-preview {
  font-size: 12px;
  color: #666;
  margin-bottom: 6px;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.message-meta {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-top: 8px;
}

.message-sender {
  font-size: 12px;
  color: #666;
  font-weight: 500;
}

.message-time {
  font-size: 11px;
  color: #999;
}

.message-actions {
  display: flex;
  gap: 8px;
  margin-left: 12px;
  opacity: 0;
  transition: opacity 0.2s;
}

.message-item:hover .message-actions {
  opacity: 1;
}

/* 消息详情弹窗样式 */
.message-detail-dialog .el-dialog__body {
  padding: 20px;
}

.detail-content {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.detail-item {
  display: flex;
  align-items: flex-start;
  font-size: 14px;
}

.detail-item.full-width {
  flex-direction: column;
  align-items: flex-start;
  gap: 8px;
}

.detail-label {
  color: #666;
  width: 80px;
  flex-shrink: 0;
  font-weight: 500;
}

.detail-value {
  color: #333;
  font-weight: 500;
}

.detail-value.unread-status {
  color: #ff4d4f;
  font-weight: 600;
}

.detail-value.read-status {
  color: #67c23a;
  font-weight: 600;
}

.detail-content-text {
  font-size: 14px;
  line-height: 1.6;
  color: #333;
  white-space: pre-wrap;
  background: #f9f9f9;
  padding: 15px;
  border-radius: 4px;
  border: 1px solid #ddd;
  min-height: 80px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 弹窗标题样式 */
.message-detail-dialog .el-dialog__header {
  border-bottom: 1px solid #eee;
  padding: 20px 20px 15px;
}

.message-detail-dialog .el-dialog__title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

/* 消息详情样式 */
.message-detail {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ddd;
}

.detail-header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #333;
  line-height: 1.3;
}

.detail-actions {
  display: flex;
  gap: 8px;
}

.detail-meta {
  margin-bottom: 25px;
}

.meta-item {
  display: flex;
  margin-bottom: 8px;
  font-size: 14px;
}

.meta-label {
  color: #666;
  width: 60px;
  flex-shrink: 0;
}

.meta-value {
  color: #333;
  font-weight: 500;
}

.detail-content {
  font-size: 14px;
  line-height: 1.6;
  color: #333;
}

.detail-content :deep(br) {
  margin-bottom: 8px;
}

.no-message {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
}

/* 自定义滚动条 */
.message-list::-webkit-scrollbar {
  width: 4px;
}

.message-list::-webkit-scrollbar-track {
  background: #f5f5f5;
}

.message-list::-webkit-scrollbar-thumb {
  background: #ccc;
}

.message-list::-webkit-scrollbar-thumb:hover {
  background: #999;
}

/* 分页组件样式 */
.pagination-container {
  padding: 20px;
  display: flex;
  justify-content: center;
  border-top: 1px solid #eee;
  background: #fff;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .message-list-container {
    width: 300px;
  }
}

@media (max-width: 768px) {
  .message-center {
    flex-direction: column;
    height: auto;
  }
  
  .message-sidebar,
  .message-list-container {
    width: 100%;
    border-right: none;
    border-bottom: 1px solid #ddd;
  }
  
  .message-detail-container {
    min-height: 400px;
  }
}
</style> 